<?php
/**
 * Created by PhpStorm.
 * User: JX
 * Date: 2017/8/28
 * Time: 18:20
 */

namespace App\Http\Controllers\API\ClassGroup;


use App\Http\Controllers\Controller;
use App\Models\AdminLog;
use App\Models\ElectiveStudent;
use App\Http\Requests\SelectClassStudentRequest as Request;
use Illuminate\Support\Facades\Auth;

class ElectiveStudentController extends Controller
{
    public function field(){
        return ElectiveStudent::$fields;
    }
    public function index(Request $request)
    {
        $queryString = $request->get('query', '');
        $models =ElectiveStudent::query()
            ->where('student_name', 'like', '%' . $queryString . '%')
            ->paginate();
        return $models;
    }


    /**
     * 添加科室
     * @param Request $request
     * @return mixed
     */
    public function store(Request $request)
    {
        $model = new ElectiveStudent();
        $model->fill($request->all());
        $logs = new AdminLog();
        $logs->admin = Auth::user()->id;
        $logs->logs = '新增待选课学生信息：'.$model->student_name;
        if (!$logs->save()) {
            throw new \Exception('记录保存失败');
        }
        if ($model->save()) {
            return $model;
        } else {
            return response($model->getErrors()->toArray(), 406);
        }
    }


    /**
     * 修改员工
     * @param User $User
     * @param Request $request
     * @return mixed
     */
    public function update( Request $request)
    {
        $id=$request->get('id');
        $ElectiveStudent=$this->findModel($id);
        $ElectiveStudent->fill($request->all());
        $logs = new AdminLog();
        $logs->admin = Auth::user()->id;
        $logs->logs = '修改待选课学生信息：'.$ElectiveStudent->student_name;
        if (!$logs->save()) {
            throw new \Exception('记录保存失败');
        }
        if ($ElectiveStudent->save()) {
            return $ElectiveStudent;
        } else {
            return response($ElectiveStudent->getErrors()->toArray(), 406);
        }
    }


    /**
     * 删除
     * @param $id
     * @return mixed
     */
    public function destroy($id)
    {
        $model = $this->findModel($id);
        try {
            $logs = new AdminLog();
            $logs->admin = Auth::user()->id;
            $logs->logs = '删除待选课学生信息：'.$model->student_name;
            if (!$logs->save()) {
                throw new \Exception('记录保存失败');
            }
            $model->delete();
            return ['state' => 'success'];
        } catch (\Exception $e) {
            return ['state' => 'failed', 'message' => $e->getMessage()];
        }
    }


    /**
     * 返回单个实例
     * @param User $user
     * @return mixed
     */
    public function show($id)
    {
        return $this->findModel($id);
    }




    /**
     * @param $id
     * @return Staff
     */
    public function findModel($id)
    {
        $model = ElectiveStudent::findOrFail($id);
        return $model;
    }
}